//
//  ChatTextView.swift
//  LearningLanguage
//
//  Created by Rui on 2023/10/7.
//

import Foundation

class Custom_TextView: UITextView {

    /// setNeedsDisplay调用drawRect
    var placeHolder: String = "" {
        didSet{
            setNeedsDisplay()
        }
    }
    
    var placeHolderColor: UIColor = UIColor.gray {
        didSet{
            setNeedsDisplay()
        }
    }
    
    override var font: UIFont? {
        didSet{
            setNeedsDisplay()
        }
    }
    
    override var text: String! {
        didSet{
            setNeedsDisplay()
        }
    }
    
    override var attributedText: NSAttributedString! {
        didSet{
            setNeedsDisplay()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        /// default字号
        self.font = 15.font_medium
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChanged(noti:)), name: UITextView.textDidChangeNotification, object: self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func textDidChanged(noti: NSNotification)  {
        setNeedsDisplay()
    }
    
    override func draw(_ rect: CGRect) {
        if hasText {
            return
        }
        var newRect = CGRect()
        newRect.origin.x = 15
        newRect.origin.y = 10
        let size = placeHolder.getStringSize(rectSize: rect.size, font: (self.font ?? 15.font_medium)!)
        newRect.size.width = size.width
        newRect.size.height = size.height
        /// 将placeHolder画在textView上
        (placeHolder as NSString).draw(in: newRect, withAttributes: [NSAttributedString.Key.font: self.font ?? 15.font_medium!,NSAttributedString.Key.foregroundColor: self.placeHolderColor])
        self.autocorrectionType = .no;//关闭自动更正
        self.spellCheckingType = .no;  //关闭检查拼写
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setNeedsDisplay()
    }
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
    @available(iOS 16.0, *)
    override func willPresentEditMenu(animator: UIEditMenuInteractionAnimating) {
        print("willPresentEditMenu=======  ")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: self)
    }
    
}

extension String {
    /// 计算字符串的尺寸
    ///
    /// - Parameters:
    ///   - text: 字符串
    ///   - rectSize: 容器的尺寸
    ///   - fontSize: 字体
    /// - Returns: 尺寸
    ///
    public func getStringSize(rectSize: CGSize,font: UIFont) -> CGSize {
        let str: NSString = self as NSString
        let rect = str.boundingRect(with: rectSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return CGSize(width: ceil(rect.width), height: ceil(rect.height))
    }
    
    /// 字符串转URL（包含判断URL的有效性）
    var toURL: URL? {
        let preticate = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
        let urlPredicateTest = NSPredicate(format: "SELF MATCHES %@", preticate)
        guard urlPredicateTest.evaluate(with: self) else { return nil }
        return URL(string: self)
    }
}
